package com.oneclick.tools.applock;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.security.Permissions;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.Service;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.KeyguardManager.KeyguardLock;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;

import com.oneclick.tools.applock.bean.PackageInfo;
import com.oneclick.tools.applock.db.PackageContentProvider;
import com.oneclick.tools.applock.pattern.ConfirmLockPattern;
import com.oneclick.tools.applock.utils.Constant;
import com.oneclick.tools.applock.utils.Log;

public class CoreService extends Service {
	
	private Process mCleanProc = null;
	private Process mLogcatProc = null;
	
	private Method setForeground = null;
	private Method startForeground = null;
	private Method stopForeground = null;
	
	private final Class<?>[] setForegroundSignature = {Boolean.TYPE};
	private final Class<?>[] startForegroundSignature = {Integer.TYPE, Notification.class};
	private final Class<?>[] stopForegroundSignature = {Boolean.TYPE};
	
	private ArrayList<PackageInfo> packages;
	
	
	private String unlockBasePackageName;
	
	public void onCreate() {
		
		Class<?> localClass = CoreService.class;
		
		try {
			setForeground = localClass.getMethod("setForeground", this.setForegroundSignature);
		} catch (Exception e) {}
		
		try {
			startForeground = localClass.getMethod("startForeground", this.startForegroundSignature);
		} catch (Exception e) {}
		
		try {
			stopForeground = localClass.getMethod("stopForeground", this.stopForegroundSignature);
		} catch (Exception e) {}
		
		startForegroundCompat();
		
		new Thread(new ReadLog()).start();
		
		KeyguardManager mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
		KeyguardLock mKeyguardLock = mKeyguardManager.newKeyguardLock("OnClick");
		mKeyguardLock.disableKeyguard();
		
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_SCREEN_ON);
		filter.addAction(Intent.ACTION_SCREEN_OFF);
		ScreenOnOffBroadcastReceiver receiver = new ScreenOnOffBroadcastReceiver();
		registerReceiver(receiver, filter);
		
		ConfirmLockPattern.LockPetternCallback callback = new ConfirmLockPattern.LockPetternCallback() {

			@Override
			public void onSuccess(Activity context) {
				Intent callIntent = context.getIntent();
				
				int on = callIntent.getIntExtra(Constant.EXTRA_ON, -1);
				int taskId = callIntent.getIntExtra(Constant.EXTRA_TASK_ID, -1);
				String packageName = callIntent.getStringExtra(Constant.EXTRA_BASE_PACKAGE_NAME);
				
				switch (on) {
				case Constant.EXTRA_ON_OPEN_APP: {
					
					ContextValues contextValues = (ContextValues) getApplication();
					contextValues.values.put(ContextValues.KEY_UNLOCK_TASK_ID, taskId);
					contextValues.values.put(ContextValues.KEY_UNLOCK_PACKAGE_NAME, packageName);
					
					context.finish();
					break;
				}
				default:
					context.finish();
					break;
				}
			}

			@Override
			public void onFailure(Activity context) {
				
			}
			@Override
			public boolean onBackPressed(Activity context) {
				return true;
			}
		};
		ConfirmLockPattern.callback = callback;
	}


	private void startForegroundCompat() {
		
		try {
			if(startForeground != null) {
				Object[] startForegroundArgs = new Object[2];
				startForegroundArgs[0] = Integer.valueOf(4);
				startForegroundArgs[1] = new Notification();
				startForeground.invoke(this, startForegroundArgs);
			}
			
			if(setForeground != null) {
				Object[] setForegroundArgs = new Object[1];
				setForegroundArgs[0] = true;
				setForeground.invoke(this, setForegroundArgs);
			}
			
		} catch (Exception e) {}
	}
	
	private void stopForegroundCompat() {
		try {
			if(stopForeground != null) {
				Object[] stopForegroundArgs = new Object[1];
				stopForegroundArgs[0] = Boolean.TRUE;
				
				stopForeground.invoke(this, stopForegroundArgs);
			}
			
			if(setForeground != null) {
				Object[] setForegroundArgs = new Object[1];
				setForegroundArgs[0] = Boolean.FALSE;
				setForeground.invoke(this, setForegroundArgs);
			}
			
		} catch (Exception e) {}
	}
	
	

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	private String getSign() {
		String startSign = "Starting activity";
		int SDKversion = Integer.valueOf(android.os.Build.VERSION.SDK);

		if (SDKversion > 8) {
			startSign = "Starting";
		}
		return startSign;
	}
	
	private void onOpenApplication() {
		
		ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		RunningTaskInfo runningTask = ((ActivityManager.RunningTaskInfo) activityManager.getRunningTasks(1).get(0));
		
		int runningTaskId = runningTask.id;
		String bPackageName = runningTask.baseActivity.getPackageName().toLowerCase().trim();
		
		Log.i("runningTaskId=" + runningTaskId);
		Log.i("bPackageName=" + bPackageName);
		
		ContextValues contextValues = (ContextValues) getApplication();
		int unlockTaskId = (Integer) contextValues.values.get(ContextValues.KEY_UNLOCK_TASK_ID);
		String unlockPackageName = (String) contextValues.values.get(ContextValues.KEY_UNLOCK_PACKAGE_NAME);
		
		
		if(runningTaskId == unlockTaskId && bPackageName.equals(unlockPackageName)) {
			// do nothing
		} else {
			if(packages == null) {
				packages = new PackageContentProvider(getApplicationContext()).queryPackages();
			}
			
			for (PackageInfo packageInfo : packages) {
				if(bPackageName.equals(packageInfo.getPackageName().toLowerCase().trim())) {
					Intent intent = new Intent(getApplicationContext(), ConfirmLockPattern.class);
					
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
					
					intent.putExtra(Constant.EXTRA_TASK_ID, runningTaskId);
					intent.putExtra(Constant.EXTRA_BASE_PACKAGE_NAME, bPackageName);
					intent.putExtra(Constant.EXTRA_ON, Constant.EXTRA_ON_OPEN_APP);
					
					startActivity(intent);
					return;
				}
			}

			if(bPackageName.equals(Constant.MAIN_PROJECT_PACKAGE_NAME)) {
				
			} else {
				contextValues.values.put(ContextValues.KEY_UNLOCK_TASK_ID, -1);
				contextValues.values.put(ContextValues.KEY_UNLOCK_PACKAGE_NAME, "");
			}
		}
		
	}
	
	public class ReadLog implements Runnable {
		
		private boolean isRun = true;
		
		public void run() {
			isRun = true;
			try {
				System.out.println(".");
				Runtime localRuntime1 = Runtime.getRuntime();
				String[] arrayOfString1 = new String[2];
				arrayOfString1[0] = "logcat";
				arrayOfString1[1] = "-c";
				CoreService.this.mCleanProc = localRuntime1
						.exec(arrayOfString1);
				CoreService.this.mCleanProc.waitFor();

				arrayOfString1[0] = "logcat";
				arrayOfString1[1] = "ActivityManager:I *:S";
				CoreService.this.mLogcatProc = localRuntime1
						.exec(arrayOfString1);
				InputStream localInputStream = CoreService.this.mLogcatProc
						.getInputStream();
				InputStreamReader localInputStreamReader = new InputStreamReader(
						localInputStream);
				BufferedReader reader = new BufferedReader(
						localInputStreamReader);
				while (isRun) {
					// 读取日志的每一行信息
					String str = reader.readLine();
					// 如果为启动activity
					if (str.contains(getSign())) {

						if(str.contains("act=android.intent.action.DELETE") && str.contains("com.android.packageinstaller")) {
							
							Intent intent = new Intent(getApplicationContext(), ConfirmLockPattern.class);
							
							intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
							
							intent.putExtra(Constant.EXTRA_ON, Constant.EXTRA_UNINTALLER);
							startActivity(intent);
						} else {
							
							onOpenApplication();
						}
					} else {
						continue;
					}
					
					
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}


		public void stop() {
			this.isRun = false;
		}
	}
	
	private class ScreenOnOffBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(Intent.ACTION_SCREEN_ON)) {
				
				Log.i("SCREEN_ON:" + Intent.ACTION_SCREEN_ON);
				
				//PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
				
//				WakeLock wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK,
//						"My Tag");
//				wakeLock.acquire();
				
				
				Intent lockScreenIntent = new Intent(getApplicationContext(), ConfirmLockPattern.class);
				lockScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(lockScreenIntent);
			} else if(action.equals(Intent.ACTION_SCREEN_OFF)) {
				Log.i("SCREEN_OFF:" + Intent.ACTION_SCREEN_OFF);
				
//				KeyguardManager mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
//				KeyguardLock mKeyguardLock = mKeyguardManager.newKeyguardLock("OnClick");
//				mKeyguardLock.disableKeyguard();
				
				Intent lockScreenIntent = new Intent(getApplicationContext(), ConfirmLockPattern.class);
				lockScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(lockScreenIntent);
			}
		}
		
	}
}
